import React, { useEffect, useState } from 'react';
import { Form, Button } from 'antd';
import AutoRenderComponent from '@/pages/WorkFlow/components/FormControls/components/AutoRenderComponent';
import { BottomAction } from '@/components';
import styles from './index.less';

const { Item } = Form;
const LARGELABEL_COL_SPAN = 8;
const SMALL_LABEL_COL_SPAN = 4;
const lagreFormWrapperLayout = {
    labelCol: { span: LARGELABEL_COL_SPAN },
    wrapperCol: { span: 24 - LARGELABEL_COL_SPAN }
};

const smallFormWrapperLayout = {
    labelCol: { span: SMALL_LABEL_COL_SPAN },
    wrapperCol: { span: 24 - SMALL_LABEL_COL_SPAN }
};

const AutoRenderForm = ({
    form,
    initialValue = {},
    formList = [],
    submitBtn = '提交', // 好像没用...
    onFormSubmit = () => {},
    layout = 'horizontal',
    appendComponent,
    onChange,
    isShowBtn, // 这个应该也没用
    formValueMap, // 流程表单
    approve, // 审批人节点数据
    status, // 流程状态
    currentCandidateFlag = 0, // 是否是当前审批人标识，1标识为登录账号为当前节点审批人
    processInstanceId // 流程实例ID
}) => {
    const { getFieldDecorator, validateFieldsAndScroll, getFieldsValue } = form;
    const [requiredArr, setRequiredArr] = useState([]);
    const fieldsValue = getFieldsValue();
    const [formStyle, setFormStyle] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);
    const [formWrapperLayout, setFormWrapperLayout] = useState(smallFormWrapperLayout);

    const handleOk = e => {
        e.preventDefault();
        validateFieldsAndScroll((err, values) => {
            if (!err) {
                onFormSubmit(values);
            }
        });
    };
    useEffect(() => {
        // 这块逻辑照搬发起审批的逻辑
        let a = [];
        const b = formList.filter(item => {
            if (item.cmpType === 'custom') {
                a = item.children.filter(subItem => {
                    // 审批预览必填字段
                    if (subItem?.isPreviewField === true) {
                        return true;
                    }
                    // 先判断proCondition和isUsed都为true
                    if ((subItem?.proCondition === true && subItem?.isUsed === true) || item?.isPreviewField === true) {
                        return subItem.rules && subItem.rules[0] && subItem.rules[0].required === true;
                    }
                    return undefined;
                });
            }
            // 审批预览必填字段
            if (item?.isPreviewField === true) {
                return true;
            }
            if ((item?.proCondition === true && item?.isUsed === true) || item?.isPreviewField === true) {
                return item.rules && item.rules[0] && item.rules[0].required === true;
            }

            return undefined;
        });

        const newData = a.concat(b);
        if (newData.length > 0) {
            setRequiredArr(newData);
        }
        if (formList && formList.length > 0) {
            // 判断没有必填项的时候传空，为空的时候要去获取审批流程节点
            if (newData.length === 0) {
                if (onChange) {
                    onChange({});
                }
            }
        }

        // 判断是否要把表单100%显示
        formList.forEach(item => (item.formStyle ? setFormStyle(true) : null));
    }, [formList]);

    let count = 0;
    useEffect(() => {
        // 监听必填项是否都有填写完成
        requiredArr.forEach(item => {
            Object.keys(fieldsValue).forEach(subItem => {
                if (item.formId === subItem) {
                    if (fieldsValue[subItem] && String(fieldsValue[subItem]).length > 0) {
                        count += 1;
                        if (count === requiredArr.length) {
                            if (onChange) {
                                onChange(fieldsValue);
                            }
                        }
                    }
                }
            });
        });
    }, [JSON.stringify(fieldsValue)]);

    useEffect(() => {
        if (formStyle === true) {
            setFormWrapperLayout(smallFormWrapperLayout);
        } else {
            setFormWrapperLayout(lagreFormWrapperLayout);
        }
    }, [formStyle]);

    return (
        <Form
            {...formWrapperLayout}
            onSubmit={handleOk}
            layout={layout}
            className={`${formStyle ? `${styles.formCtr1}` : `${styles.formCtr}`}`}
        >
            {formList.map(item => {
                if (item.tag === 'Turnover') {
                    item.options = { employeeCode: item.employeeCode };
                }

                if (item.tag === 'PostApply') {
                    item.options = { id: item?.postApplyId, reason: item?.reason };
                }

                // 离职交接传入数据源
                if (item.tag === 'Handover') {
                    item.formValueMap = formValueMap;
                }

                if (item.tag === 'LackCard') {
                    item.options = { employeeCode: item?.employeeCode };
                }

                const commonLayout = () => {
                    if (item.cmpType === 'common') {
                        if ((!item.label || item.label === '') && item.tag !== 'Title') {
                            return {
                                wrapperCol: {
                                    span: formWrapperLayout?.wrapperCol?.span,
                                    offset: formWrapperLayout?.labelCol?.span
                                }
                            };
                        }
                        if (formStyle === true && formList?.children?.length > 0) {
                            return smallFormWrapperLayout;
                        }
                        return lagreFormWrapperLayout;
                    }
                    return null;
                };

                return item.cmpType === 'common' ? (
                    <div key={item.key} className={`${formStyle ? `${styles.formCtr}` : `${styles.formCtr2}`}`}>
                        <Item label={item.tag === 'Title' ? null : item.label} extra={item.extra} {...commonLayout()}>
                            {getFieldDecorator(item.formId, {
                                rules: item.rules,
                                initialValue: initialValue[item.formId] || item.initialValue
                            })(
                                <AutoRenderComponent
                                    form={form}
                                    config={item}
                                    approve={approve}
                                    status={status}
                                    currentcandidateflag={currentCandidateFlag}
                                    processInstanceId={processInstanceId}
                                />
                            )}
                        </Item>
                    </div>
                ) : (
                    <AutoRenderComponent
                        key={item.key}
                        form={form}
                        config={item}
                        wrapperLayout={formWrapperLayout}
                        formValueMap={formValueMap}
                        approve={approve}
                        status={status}
                        currentcandidateflag={currentCandidateFlag}
                        processInstanceId={processInstanceId}
                        setSubmitLoading={setSubmitLoading}
                        tag={item.tag}
                    />
                );
            })}
            {appendComponent || ''}
            {isShowBtn ? (
                <Form.Item>
                    <BottomAction>
                        <Button type="primary" htmlType="submit" loading={submitLoading}>
                            {submitBtn}
                        </Button>
                    </BottomAction>
                </Form.Item>
            ) : null}
        </Form>
    );
};

export default Form.create()(AutoRenderForm);
